﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;

namespace Milan.Deploy
{
	/// <summary>
	/// This picks up files from the log directory and sends them to the server.
	/// When an crash is received,
	/// </summary>
	public class Reporter : DirectoryWatcher
	{
		public Reporter(Application application)
			: base(application, Path.Combine(Settings.LoggingFolder, "send"), NotifyFilters.LastWrite)
		{
			OnChange(m_directory, WatcherChangeTypes.Changed);
			m_sentDirectory = Path.Combine(Settings.LoggingFolder, "sent");
			if (!Directory.Exists(m_sentDirectory))
				Directory.CreateDirectory(m_sentDirectory);
		}
		protected string m_sentDirectory;
		/// <summary>
		/// This function will send any log files in the directory
		/// </summary>
		protected override void OnChange(string filePath, WatcherChangeTypes changeType)
		{
			foreach (var file in Directory.EnumerateFiles(m_directory, "*.*"))
			{
				try {
					var client = new Client();
					// The sent directory is where the file will be moved after it has been sent
					var dest = Path.Combine(m_sentDirectory,Path.GetFileName(file));
					// Check if the file already exists and if so and is the same, then do not send.
					// If the file is not the same, then 
					bool isSame = false;
					if (File.Exists(dest))
					{
						isSame = File.ReadLines(file).SequenceEqual(File.ReadLines(dest));
						if (!isSame)
							File.Delete(dest);
					}
					if (!isSame)
					{
						client.UploadLogFile(file);
						File.Move(file, dest);
					}
				}
				catch (Exception)
				{
				}
			}
		}
	}
}
